package com.clothes.act;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.LayoutRes;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.clothes.app.AtyContainer;
import com.clothes.utils.DateTool;
import com.gyf.barlibrary.ImmersionBar;
import com.lzy.okgo.OkGo;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public abstract class BaseActivity extends FragmentActivity {

    protected ImmersionBar mImmersionBar;
    protected int pageNum,pageSize = 20;
    protected Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    onSuccess((String) msg.obj);
                    break;
                case 2:
                    onError((String) msg.obj);
                    break;
                case 3:
                    showToast("服务器连接失败");
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AtyContainer.getInstance().addActivity(this);
        mImmersionBar = ImmersionBar.with(this);
        initView();
        initData();
    }

    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        super.setContentView(layoutResID);
        ButterKnife.bind(this);
    }

    public abstract void initView();
    public abstract void initData();

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        if (mImmersionBar != null) {
            mImmersionBar.destroy();
        }
        if(timePickerView != null)
            timePickerView = null;
        AtyContainer.getInstance().removeActivity(this);
    }

    // 显示提示
    protected void showToast(String txt){
        Toast.makeText(this,txt, Toast.LENGTH_SHORT).show();
    }

    //跳转 带intent
    protected void goToActivity(Class to, Intent intent){
        intent.setClass(this,to);
        startActivity(intent);
    }

    //
    protected void showDialog(String s1, String cancel, String sure){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(s1);
        builder.setNegativeButton(cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                negative(dialog);
            }
        });
        builder.setPositiveButton(sure, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                positive(dialog);
            }
        });
        builder.create().show();
    }

    protected void negative(DialogInterface dialog){

    }
    protected void positive(DialogInterface dialog){}

    protected double parseDouble(String num){
        if(num == null || num.equals(""))
            return 0;
        else
            return Double.parseDouble(num);
    }

    protected int parseInt(String num){
        if(num == null || num.equals(""))
            return 0;
        else
            return Integer.parseInt(num);
    }

    public MediaType JSON=MediaType.parse("application/json; charset=utf-8");
    public void post(String json,String Url){
        RequestBody requestBody = RequestBody.create(JSON, json);
        Request request = new Request.Builder().post(requestBody).url(Url).build();
        OkGo.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message message = new Message();
                message.what = 3;
                handler.sendMessage(message);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                try {
                    JSONObject obj = new JSONObject(res);
                    if(obj.has("code")){
                        int code = obj.getInt("code");
                        if(code == 200){
                            Message message = new Message();
                            message.what = 1;
                            message.obj = res;
                            handler.sendMessage(message);
                        }else {
                            Message message = new Message();
                            message.what = 2;
                            message.obj = obj.getString("message");
                            handler.sendMessage(message);
                        }
                    }else {
                        int status = obj.getInt("status");
                        if(status == 200){
                            Message message = new Message();
                            message.what = 1;
                            message.obj = res;
                            handler.sendMessage(message);
                        }else {
                            Message message = new Message();
                            message.what = 2;
                            message.obj = obj.getString("message");
                            handler.sendMessage(message);
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    public void put(String json,String Url){
        RequestBody requestBody = RequestBody.create(JSON, json);
        Request request = new Request.Builder().put(requestBody).url(Url).build();
        OkGo.getInstance().getOkHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message message = new Message();
                message.what = 3;
                handler.sendMessage(message);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                try {
                    JSONObject obj = new JSONObject(res);
                    if(obj.has("code")){
                        int code = obj.getInt("code");
                        if(code == 200){
                            Message message = new Message();
                            message.what = 1;
                            message.obj = res;
                            handler.sendMessage(message);
                        }else {
                            Message message = new Message();
                            message.what = 2;
                            message.obj = obj.getString("message");
                            handler.sendMessage(message);
                        }
                    }else {
                        int status = obj.getInt("status");
                        if(status == 200){
                            Message message = new Message();
                            message.what = 1;
                            message.obj = res;
                            handler.sendMessage(message);
                        }else {
                            Message message = new Message();
                            message.what = 2;
                            message.obj = obj.getString("message");
                            handler.sendMessage(message);
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    protected void onSuccess(String res){

    }
    protected void onError(String msg){
        showToast(msg);
    }

    //设置时间
    protected TimePickerView timePickerView;
    protected void setTime(final int num){
        Calendar calendar = Calendar.getInstance();
        timePickerView = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                if(num != 3)
                    setTimeText(DateTool.getStringDate(date,"yyyy-MM-dd HH:mm"));
                else
                    setTimeText(DateTool.getStringDate(date,"yyyy-MM-dd"));
            }
        })
                .setType(new boolean[]{true, true, true, true, true, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setSubCalSize(15)
                .setContentTextSize(18)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleText("时间")//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setTitleColor(Color.WHITE)//标题文字颜色
                .setSubmitColor(Color.WHITE)//确定按钮文字颜色
                .setCancelColor(Color.WHITE)//取消按钮文字颜色
                .setTitleBgColor(0xFF3F51B5)//标题背景颜色 Night mode
                .setBgColor(0xFFB0C4DE)//滚轮背景颜色 Night mode
                .setDate(calendar)// 如果不设置的话，默认是系统时间*/
//                .setRangDate(startDate,endDate)//起始终止年月日设定
                .setLabel("年","月","日","时","分","秒")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(true)//是否显示为对话框样式
                .build();
    }

    protected void setTimeText(String time){

    }

}
